﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QiAdmin.Core.Utils
{
    public class ConvertUtil
    {
        public static object? ConvertValue(string value, Type targetType)
        {
            try
            {
                if (targetType == typeof(string))
                {
                    return value;
                }
                else if (targetType.IsEnum)
                {
                    return Enum.Parse(targetType, value, true);
                }
                else if (targetType == typeof(int) || Nullable.GetUnderlyingType(targetType) == typeof(int))
                {
                    return int.Parse(value, CultureInfo.InvariantCulture);
                }
                else if (targetType == typeof(long) || Nullable.GetUnderlyingType(targetType) == typeof(long))
                {
                    return long.Parse(value, CultureInfo.InvariantCulture);
                }
                else if (targetType == typeof(float) || Nullable.GetUnderlyingType(targetType) == typeof(float))
                {
                    return float.Parse(value, CultureInfo.InvariantCulture);
                }
                else if (targetType == typeof(double) || Nullable.GetUnderlyingType(targetType) == typeof(double))
                {
                    return double.Parse(value, CultureInfo.InvariantCulture);
                }
                else if (targetType == typeof(decimal) || Nullable.GetUnderlyingType(targetType) == typeof(decimal))
                {
                    return decimal.Parse(value, CultureInfo.InvariantCulture);
                }
                else if (targetType == typeof(bool) || Nullable.GetUnderlyingType(targetType) == typeof(bool))
                {
                    return bool.Parse(value);
                }
                else if (targetType == typeof(DateTime) || Nullable.GetUnderlyingType(targetType) == typeof(DateTime))
                {
                    return DateTime.Parse(value, CultureInfo.InvariantCulture);
                }
                else if (targetType == typeof(Guid) || Nullable.GetUnderlyingType(targetType) == typeof(Guid))
                {
                    return Guid.Parse(value);
                }
                else
                {
                    // 尝试使用 TypeConverter 进行转换  
                    var converter = TypeDescriptor.GetConverter(targetType);
                    if (converter.CanConvertFrom(typeof(string)))
                    {
                        return converter.ConvertFromString(value);
                    }
                }
            }
            catch { }
            return null;
        }
    }
}
